package com.burst.reptile.modular.system.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.burst.reptile.common.constant.UserConstants;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.framework.aspectj.lang.annotation.Log;
import com.burst.reptile.framework.aspectj.lang.enums.BusinessType;
import com.burst.reptile.framework.web.controller.BaseController;
import com.burst.reptile.framework.web.result.Result;
import com.burst.reptile.modular.system.entity.SysDept;
import com.burst.reptile.modular.system.service.ISysDeptService;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;

/**
 * <p>
 * 部门表 前端控制器
 * </p>
 *
 * @author wujin
 * @since 2020-05-22
 */
@RestController
@RequestMapping("/system/dept")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysDeptController extends BaseController {

	private final ISysDeptService deptService;

	/**
	 * 获取部门列表
	 */
	@PreAuthorize("@ss.hasPermi('system:dept:list')")
	@GetMapping("/list")
	public Result<List<SysDept>> list(SysDept dept) {
		List<SysDept> depts = deptService.selectDeptList(dept);
		return Result.success(depts);
	}

	/**
	 * 查询部门列表（排除节点）
	 */
	@PreAuthorize("@ss.hasPermi('system:dept:list')")
	@GetMapping("/list/exclude/{deptId}")
	public Result<List<SysDept>> excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
		List<SysDept> depts = deptService.selectDeptList(new SysDept());
		Iterator<SysDept> it = depts.iterator();
		while (it.hasNext()) {
			SysDept d = (SysDept) it.next();
			if (d.getDeptId().intValue() == deptId
					|| ArrayUtils.contains(StrUtil.splitToArray(d.getAncestors(), ","), deptId + "")) {
				it.remove();
			}
		}
		return Result.success(depts);
	}

	/**
	 * 根据部门编号获取详细信息
	 */
	@PreAuthorize("@ss.hasPermi('system:dept:query')")
	@GetMapping(value = "/{deptId}")
	public Result<Object> getInfo(@PathVariable Long deptId) {
		return Result.success(deptService.getById(deptId));
	}

	/**
	 * 获取部门下拉树列表
	 */
	@GetMapping("/treeselect")
	public Result<Object> treeselect(SysDept dept) {
		List<SysDept> depts = deptService.selectDeptList(dept);
		return Result.success(deptService.buildDeptTreeSelect(depts));
	}

	/**
	 * 加载对应角色部门列表树
	 */
	@GetMapping("/roleDeptTreeselect/{roleId}")
	public Result<Object> roleDeptTreeselect(@PathVariable("roleId") Long roleId) {
		List<SysDept> depts = deptService.selectDeptList(new SysDept());
		Map<String, Object> map = new HashMap<>();
		List<Long> ids = deptService.selectDeptListByRoleId(roleId);
		List<String> checkedKeys = new ArrayList<>();
		if(ToolUtil.isNotEmpty(ids)) {
			checkedKeys = ids.stream().map(i -> i.toString()).collect(Collectors.toList());
		}
		map.put("checkedKeys", checkedKeys);
		map.put("depts", deptService.buildDeptTreeSelect(depts));
		return Result.success(map);
	}

	/**
	 * 新增部门
	 */
	@PreAuthorize("@ss.hasPermi('system:dept:add')")
	@Log(title = "部门管理", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	public Result<Object> add(@Validated @RequestBody SysDept dept) {
		if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
			return Result.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
		}
		return Result.success(deptService.insertDept(dept));
	}

	/**
	 * 修改部门
	 */
	@PreAuthorize("@ss.hasPermi('system:dept:edit')")
	@Log(title = "部门管理", businessType = BusinessType.UPDATE)
	@PutMapping("/edit")
	public Result<Object> edit(@Validated @RequestBody SysDept dept) {
		if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
			return Result.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
		} else if (dept.getParentId().equals(dept.getDeptId())) {
			return Result.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
		} else if (StrUtil.equals(UserConstants.DEPT_DISABLE, dept.getDeptStatus())
				&& deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0) {
			return Result.error("该部门包含未停用的子部门！");
		}
		return Result.success(deptService.updateDept(dept));
	}

	/**
	 * 删除部门
	 */
	@PreAuthorize("@ss.hasPermi('system:dept:remove')")
	@Log(title = "部门管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/remove/{deptId}")
	public Result<Object> remove(@PathVariable Long deptId) {
		if (deptService.hasChildByDeptId(deptId)) {
			return Result.error("存在下级部门,不允许删除");
		}
		if (deptService.checkDeptExistUser(deptId)) {
			return Result.error("部门存在用户,不允许删除");
		}
		return Result.success(deptService.deleteDeptById(deptId));
	}
}
